import React, { useState, useEffect } from "react";
import UpdateNotifier from "../core/updateNotifier";

const ReactUpdateNotifier = (props) => {
  const [show, setShow] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [notifier, setNotifier] = useState(null);

  const {
    options = {},
    features = ["性能优化", "问题修复"],
    onUpdate,
    onBeforeRefresh,
    styles, // 接收样式属性
  } = props;
  // 注入样式到页面
  useEffect(() => {
    if (styles) {
      const styleElement = document.createElement("style");
      styleElement.textContent = styles;
      document.head.appendChild(styleElement);

      return () => {
        document.head.removeChild(styleElement);
      };
    }
  }, [styles]);

  useEffect(() => {
    const instance = new UpdateNotifier({
      ...options,
      autoRefresh: options.autoRefresh !== false,
    });

    setAutoRefresh(instance.options.autoRefresh);
    setNotifier(instance);

    // 监听事件
    instance.on("update", (version) => {
      setShow(true);
      if (onUpdate) onUpdate(version);
    });

    instance.on("beforeRefresh", (seconds) => {
      setCountdown(seconds);
      if (onBeforeRefresh) onBeforeRefresh(seconds);
    });

    return () => {
      instance.destroy();
    };
  }, []);

  const refresh = () => {
    if (notifier) notifier.refreshPage();
  };

  const delay = () => {
    setShow(false);
    // 10分钟后重新检查
    setTimeout(() => {
      if (notifier) notifier.checkUpdate();
    }, 10 * 60 * 1000);
  };

  const close = () => {
    setShow(false);
    if (notifier && notifier.countdownTimer) {
      clearInterval(notifier.countdownTimer);
      notifier.countdownTimer = null;
    }
  };

  if (!show) return null;

  return (
    <div className="update-notifier">
      <div className="notification">
        <div className="notification-header">
          <h3>发现新版本</h3>
          <button className="close-btn" onClick={close}>
            ×
          </button>
        </div>
        <div className="notification-body">
          <p>检测到新版本可用，新版本包含以下改进：</p>
          <ul>
            {features.map((feature, index) => (
              <li key={index}>{feature}</li>
            ))}
          </ul>
          {autoRefresh && (
            <p className="countdown">页面将在 {countdown} 秒后自动刷新</p>
          )}
        </div>
        <div className="notification-actions">
          <button className="refresh-btn" onClick={refresh}>
            立即刷新
          </button>
          {!autoRefresh && (
            <button className="delay-btn" onClick={delay}>
              稍后提醒
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

// 添加默认样式（可选）
ReactUpdateNotifier.defaultProps = {
  features: ['性能优化', '问题修复'],
  options: {},
  styles: `
    .update-notifier {
      position: fixed;
      bottom: 20px;
      right: 20px;
      z-index: 10000;
    }
    .notification {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      max-width: 400px;
      width: 90vw;
      overflow: hidden;
    }
    .notification-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      background: #1890ff;
      color: white;
    }
    .notification-header h3 {
      margin: 0;
      font-size: 18px;
    }
    .close-btn {
      background: none;
      border: none;
      color: white;
      font-size: 24px;
      cursor: pointer;
      padding: 0;
      line-height: 1;
    }
    .notification-body {
      padding: 16px;
      border-bottom: 1px solid #eee;
    }
    .notification-body p {
      margin: 0 0 10px;
    }
    .notification-body ul {
      padding-left: 20px;
      margin: 10px 0;
    }
    .notification-body li {
      margin-bottom: 5px;
    }
    .countdown {
      font-weight: bold;
      color: #f5222d;
    }
    .notification-actions {
      display: flex;
      padding: 12px 16px;
      justify-content: flex-end;
      gap: 10px;
    }
    .notification-actions button {
      padding: 8px 16px;
      border-radius: 4px;
      border: none;
      cursor: pointer;
      font-weight: 500;
    }
    .refresh-btn {
      background: #1890ff;
      color: white;
    }
    .delay-btn {
      background: #f5f5f5;
      color: rgba(0,0,0,0.85);
    }
  `,
};

export default ReactUpdateNotifier;
